package other;

import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.ClientConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;

import java.util.Arrays;

public class IgniteUtil {

    private static final String URI = "uri";
    private static final String URI_RANGE = "uri.range";
    private static final String TYPE = "type";

    private static final String CACHE_NAME = "TRANSACTION";

    public static void printHelp() {
        System.out.println("帮助 ：\n" +
                        "-Duri=xxx:10080\tignite组件地址\n"
//                "-Dtype=kv\t指定本次任务模式：kv 键值模式 sql sql模式"
        );
    }

    public static IgniteJobConfig parseConfig() {
        String uri = System.getProperty(URI);
//        String type = System.getProperty(TYPE);
        if (uri == null || uri.length() == 0) {
            printHelp();
            System.exit(-1);
        }
        IgniteJobConfig igniteJobConfig = new IgniteJobConfig();
        igniteJobConfig.setUri(uri);
        return igniteJobConfig;
    }


    /**
     * 准备连接ignite client 配置
     *
     * @param igniteUri ignite 集群地址
     * @return
     */
    public static ClientConfiguration init(String igniteUri) {
        ClientConfiguration cfg = new ClientConfiguration();
        String[] split = igniteUri.split(",");
        cfg.setAddresses(split);
        cfg.setTimeout(5000);
        return cfg;
    }

    public static IgniteConfiguration getIgniteConfig() {
        TcpDiscoverySpi spi = new TcpDiscoverySpi();
        TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder();
//        192.168.0.192:47500..47509
        String property = System.getProperty(URI_RANGE);
        if (property == null) {
            System.out.println("帮助 ：\n" +
                    "-Duri.range=192.168.0.192:47500..47509\tignite组件地址范围\n"
            );
        }
        ipFinder.setAddresses(Arrays.asList(property));
        spi.setIpFinder(ipFinder);
        IgniteConfiguration cfg = new IgniteConfiguration();
        cfg.setDiscoverySpi(spi);
        cfg.setClientMode(true);
        return cfg;
    }

    public static CacheConfiguration<Object, Object> getCacheConfig() {
        //client cache 配置
        CacheConfiguration<Object, Object> clientCacheConfiguration = new CacheConfiguration<>();
        clientCacheConfiguration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
        clientCacheConfiguration.setName(CACHE_NAME);
        clientCacheConfiguration.setBackups(1);
        return clientCacheConfiguration;
    }


}
